#根据传入的台站号和通道号绘制
"""
    完成了补数方法（新格式）
    缺少采样方法
    缺少异常捕获
    缺少应对数据重复的对策
    缺少label自适应显示方法
"""

import math
import os
import warnings
from datetime import datetime, timedelta, time

import numpy as np
import matplotlib as mpl
from matplotlib import pyplot as plt

from stressPrinter.Model import Globalvariables


def graphPrinter(group,labelGroup):
    warnings.filterwarnings("ignore", category=UserWarning)
    SAMP = Globalvariables.SAMP
    COPY = Globalvariables.COPY
    days = len(Globalvariables.SELECT_DATE) - 1
    if SAMP == 1:
        slimp = 4
    elif SAMP == 2:
        slimp = 240
    else:
        slimp = 1
    mpl.rcParams['font.size'] = 18
    plt.figure(figsize=(20, 7))
    plt.rcParams['font.sans-serif'] = ['SimHei']  # 用来正常显示中文标签
    plt.title('5305轨道顺槽数据对比')
    plt.ylabel("Mpa")
    maxLim = 0
    minLim = math.inf
    for i in range(len(group)):
        prev_value = None
        content = []
        x = np.arange(2)
        limCount = 0
        for y in group[i]:
            limCount += 1
            y = float(y)
            if y > 0:
                if y > maxLim:
                    maxLim = y
                if y < minLim:
                    minLim = y
                content.append(y)
                prev_value = y
            elif y <= 0:
                if COPY == 1:
                    content.append(prev_value)
                else:
                    content.append(np.nan)
        x = np.arange(0, limCount * 15, 15 * slimp)
        if  labelGroup == []:

            plt.plot(x, content, label=Globalvariables.LABEL[i])
        else:
            plt.plot(x, content, label=Globalvariables.LABEL[i]+','+labelGroup[i])
    plt.xlim(0, days * 86400)  # 分钟除以4 小时除以240
    print()
    plt.xticks(np.arange(0, (days+1)*86400, 86400), Globalvariables.SELECT_DATE)
    plt.ylim(minLim - 0.2, maxLim + 0.2)
    plt.yticks(np.arange(math.floor(minLim), maxLim + 0.2, 1))
    plt.legend(loc='upper left', bbox_to_anchor=(1, 1), fontsize=10)
    plt.tight_layout()
    #plt.savefig(save_path)
    plt.show()
def disposeData(lines,index):
    SAMP = Globalvariables.SAMP
    content = []
    firstTag = 0    #初次标记
    ltime = datetime(year=2024, month=1, day=1, hour=0, minute=0, second=0)
    for line in lines:
        mytime = datetime.strptime(line.split(',')[0], "%Y-%m-%d %H:%M:%S")
        if firstTag == 0:
            if str(mytime.time()) != '00:00:00':
                # lNum = mytime.time().hour*3600 + mytime.time().minute*60 + mytime.time().second / 15  # 缺失数量
                # for i in range(int(lNum)):
                #     content.append(0)
                ctime = mytime
                endtime = ctime.replace(hour=00, minute=00, second=00)
                lNum = abs((endtime - mytime).total_seconds()) / 15
                for i in range(int(lNum)):
                    content.append(0)
                #print("缺失第一条数据！")
            ltime = mytime
            content.append(line.split(',')[index])
            firstTag = 1
        else:
            if abs((mytime - ltime).total_seconds()) > 15:      #缺失数据
                lNum = abs((mytime - ltime).total_seconds()) / 15   #缺失数量
                for i in range(int(lNum)):
                    content.append(0)
            content.append(line.split(',')[index])
            ltime = mytime
    if len(content) != 5760:    #尾数缺了
        mytime = datetime.strptime(lines[-1].split(',')[0], "%Y-%m-%d %H:%M:%S")
        if str(mytime.time()) != '23:59:45':
            endtime = mytime.replace(hour=23, minute=59, second=45)
            lNum = abs((endtime - mytime).total_seconds()) / 15
            for i in range(int(lNum)):
                content.append(0)
    if Globalvariables.SAMP>0:
        content = myslimping(content)
    #print(content)
    return content
def myslimping(content):
    SAMP = Globalvariables.SAMP
    result = []
    time = 0
    if SAMP == 1:
        time = 4
    if SAMP == 2:
        time = 240
    if time != 0:    #分钟采样，4个为一组
        t1 = 0
        n = 0
        i = 0
        for c in content:
            t2 = float(c)
            if t2 > 0:
                n += 1
                t1 += t2
            if i % time == 0:
                if n == 0:
                    result.append('0')
                else:
                    result.append(str(t1/n))
                n = 0
                t1 = 0
            i += 1
    return result

def mySlimping_old(lines,index):
    #根据slimp值决定数据采样率
    #slimp：0-原始采样，1-分钟采样，2-小时采样
    #分钟和小时采样时，遇到小于等于0的值将替换为上一个值
    SAMP = Globalvariables.SAMP
    content = []
    time = 0
    if SAMP == 1:
        time = 4
    if SAMP == 2:
        time = 240
    if SAMP == 0:      #原始采样
        content = [line.split(',')[index-1] for line in lines]
    if time != 0:    #分钟采样，4个为一组
        t1 = 0
        n = 0
        i = 0
        for line in lines:
            t2 = float(line.split(',')[index-1])
            if t2 > 0:
                n += 1
                t1 += t2
            if i % time == 0:
                if n == 0:
                    content.append(0)
                else:
                    content.append(t1/n)
                n = 0
                t1 = 0
            i += 1
    return content
def complete_date_list(date_list):
    #根据开始和结束日期补完中间日期
    # 将字符串转换为datetime对象
    dates = [datetime.strptime(date, '%Y-%m-%d') for date in date_list]
    # 获取第一个日期和最后一个日期
    start_date = dates[0]
    end_date = dates[1]
    # 创建一个空的列表来保存补全的日期
    completed_dates = []
    # 循环从开始日期到结束日期，每次增加一天，并将日期添加到列表中
    current_date = start_date
    if current_date>end_date:
        raise ValueError("结束日期不能早于开始日期！")
    while current_date <= end_date:
        completed_dates.append(current_date.strftime('%Y-%m-%d'))
        current_date += timedelta(days=1)
    return completed_dates
def get_file_names(foldPath):
    #获取目录下所有通道名称
    filenames = []
    for filename in os.listdir(foldPath):
        filenames.append(filename)
    return filenames
def get_fileByname(name,folder,dates):
    #根据通道名称获取文件夹下所有数据内容
    stressFile = []
    for foldername, subfolders, filenames in os.walk(folder):
        for filename in filenames:
            if name in filename:
                for date in dates:
                    if '' + name + '_' + date in filename:
                        stressFile.append(filename)
    if stressFile == []:
        raise ValueError("对应日期文件不存在！")
    return stressFile
def create_dict_from_list(lst):
    #返回台站列表和对应的通道列表（下标对应）
    station = []
    tunnel = []
    for item in lst:
        key, value = item.split('_')
        station.append(key)
        tunnel.append(int(value))
    return station, tunnel

def find_indices(s, c):
    indices = []
    for i, item in enumerate(s):
        if item == c:
            indices.append(i)
    return indices
def remove_elements_at_indices(station,i):
    # 创建一个新的列表，只包含 s 中不在 i 索引位置的元素
    return [elem for idx, elem in enumerate(station) if idx not in i]
# def read_stressFile_new(stressFile,name,foldPath,i):
#     file_path = foldPath + "/" + name + "/" + stressFile
#     try:
#         with open(file_path, 'r') as file:
#             # 读取第二行开始所有的内容
#             lines = file.readlines()[1:]
#             if len(lines) < 5760:   #数据不完整
#                 content = disposeData(lines,Globalvariables.TUNNEL[i])
#             else:
#                 content = mySlimping(lines, Globalvariables.TUNNEL[i])
#             return content
#     except FileNotFoundError:
#         print(f"文件 {file_path} 未找到.")
#         return None
def read_stressFile(stressFile,name,foldPath,i):
    #旧数据格式
    #sampling：0-原始采样，1-分钟采样，2-小时采样
    file_path = foldPath+"/"+name+"/"+stressFile
    try:
        with open(file_path, 'r') as file:
            # 读取第二行开始所有的内容
            lines = file.readlines()[1:]
            content = disposeData(lines, Globalvariables.TUNNEL[i])#新数据格式
            #content = mySlimping(lines,Globalvariables.TUNNEL[i])#旧数据格式
            # if content == []:
            #     raise ValueError("对应日期文件不存在！")
            return content
    except FileNotFoundError:
        print(f"文件 {file_path} 未找到.")
        return None
def initData(labelGroup):
    dates = complete_date_list(Globalvariables.SELECT_DATE)   #补完日期
    Globalvariables.LABEL = Globalvariables.STATION  # LABEL
    station,tunnel = create_dict_from_list(Globalvariables.STATION)
    Globalvariables.STATION = station
    Globalvariables.TUNNEL =tunnel
    foldNames = get_file_names(Globalvariables.FOLDPATH)
    group = []  # 组数组
    for name in foldNames:
        station = Globalvariables.STATION
        tunnel = Globalvariables.TUNNEL
        if name in station:     #确定台站号
            indices = find_indices(station,name)    #记录对应台站参与绘制的通道数量
            stressFile = get_fileByname(name, Globalvariables.FOLDPATH, dates)
            for i in indices:
                stressContent = []
                for file in stressFile:
                    content = read_stressFile(file, name, Globalvariables.FOLDPATH,i)
                    stressContent += content
                group.append(stressContent)
            Globalvariables.TUNNEL = remove_elements_at_indices(tunnel,indices)
            Globalvariables.STATION = remove_elements_at_indices(station,indices)
    Globalvariables.SELECT_DATE = dates
    Globalvariables.SELECT_DATE.append("")
    graphPrinter(group,labelGroup)